part of '../button.dart';

/// 按钮的核心组件
/// 将某个组件编程"可点击"状态，提供一个动画的controller（只读）
/// 通过controller的值来控制动画效果
class LxClickable extends StatelessWidget {
  /// 如果为null，则无法点击
  final VoidCallback? onClick;
  final VoidCallback? onLongClick;

  final Duration? duration;

  /// 通过controller.value来控制动画
  final Widget Function(AnimationController) builder;

  /// 自行指定鼠标的样式
  final MouseCursor? mouse;
  const LxClickable({
    required this.onClick,
    this.onLongClick,
    required this.builder,
    this.duration,

    /// 使用[SystemMouseCursors]指定
    this.mouse,
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    final _duration = duration ?? const Duration(milliseconds: 100);
    final bool isValid = onClick != null;

    return AnimationFast(
      duration: _duration,
      builder: (controller) {
        return GestureDetector(
          onLongPress: onLongClick,
          onTap: onClick,
          // 当鼠标点击时，会瞬间回到原来的状态，而当点击结束时，则会慢慢恢复
          onTapDown: (_) => controller.value = 0,
          onTapUp: (_) => isValid ? controller.forward() : null,
          child: MouseRegion(
            /// 每当鼠标移入时，会触发controller.forward，退出区域则反之
            onEnter: (_) => isValid ? controller.forward() : null,
            onExit: (_) => isValid ? controller.reverse() : null,
            // 如果无法点击，鼠标为禁止样式，否则是点击样式
            cursor: onClick == null
                ? SystemMouseCursors.forbidden
                : (mouse ?? SystemMouseCursors.click),
            child: builder(controller),
          ),
        );
      },
    );
  }
}
